﻿using MoetutuServer.Helper;
using MoetutuServer.Pixiv;
using MoetutuServer.Pixiv.ProcessImg;
using MoetutuServer.PublishHelper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MoetutuServer.WebSite.Pixiv
{
    class Scanner
    {
        public static void Start()
        {

            for (int i = 1; i < 11; i++)
            {
                StaticValue.Tip = string.Format("当前分析{0}页", i);
                //&date=20180107
                AnalysisPage(string.Format("https://www.pixiv.net/ranking.php?mode=weekly&p={0}&format=json", i));
            }
            Console.WriteLine("全部解析完成");
        }

        public static void AnalysisPage(String url)
        {
            Console.WriteLine(url);
            String Shtml = WebHelper.HttpGet(url);

            Shtml = TextHelper.ReplaceText(Shtml, "\"illust_series\":{[\\w\\W]*?}", "\"illust_series\": false");//替换掉会导致异常的漫画信息
            try
            {

                PixivJson.Root AllJson = JsonConvert.DeserializeObject<PixivJson.Root>(Shtml);

                foreach (PixivJson.Contents single in AllJson.contents)
                {
                 
                        if (ImgQualified(single))
                    {
                        if (PixivHelper.ReflushLog(single.illust_id))//如果没下载过就不跳出。
                            continue;
                        String Imgurl = GetImg("https://i.pximg.net/img-original" + TextHelper.RegexText(single.url, "/img/[0-9].*?/[0-9].*?/[0-9].*?/[0-9].*?/[0-9].*?/[0-9].*?/") + single.illust_id + "_p0");
                            Console.WriteLine(Imgurl);
                            if (Imgurl != "")
                            {

                         
                       
                            Console.WriteLine("开始处理！");
                                List<String> ImgList =  UploadImg.GetPicBed(Imgurl, "Pixiv");
                              
                                if (ImgList.Count >=2 )
                                {
                                    List<String> TagListTemp = TagHelper.TranslateTag(single.tags);//首先进行一次汉化处理

                                    TagListTemp.Add("Pixiv Id " + single.user_id);
                                      string Content= CreateContent.EstablishContent(TagListTemp, ImgList);
                                    string Title = CreateTitle.Title(single.tags);
                                    Console.WriteLine("准备发布 ");
                                  
                                
                                    PostHelper.WordPressPostHelper.Publish(StaticValue.PostUser, Title, Content, TagListTemp, single.url, new List<int>() {  1 });
                                }


                            }
                            else
                                Console.WriteLine("已经扫描过，跳过");

                        }

                }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);

            }

        }
        /// <summary>
        /// 判断图片是否合格
        /// </summary>
        /// <param name="single"></param>
        /// <returns></returns>
        private static bool ImgQualified(PixivJson.Contents single)
        {
            if (!PixivHelper.TagIdentify(single.tags))
            {
                Console.WriteLine("所有tag不合格");
                PrintLog.Log("------------------------"+single.illust_id);
                return false;
            }


            foreach (string Tag in single.tags)
            {

                if (StaticValue.ExcludeKey.Contains(Tag))
                {
                    PrintLog.Log("非法关键词，跳出！" + Tag);
                    return false;
                }
            }


            if (StaticValue.ExcludeKey.Contains(single.user_id + ""))
            {
                Console.WriteLine("需要屏蔽的画师");

                return false;
            }

            if (single.illust_page_count > 1)
            {
                Console.WriteLine("漫画需要屏蔽");
                return false;
            }

            if (single.rating_count < 1000 || ((float)single.width / single.height < 0.25))
            {
                PrintLog.Log("需要屏蔽 图片比例{0}，得分{1}，ID:{2}", ((float)single.width / single.height), single.rating_count, single.illust_id);
                return false;
            }
            Console.WriteLine("可下载，ID{0}，评分{1}", single.illust_id, single.rating_count);
            return true;
        }
        /// <summary>
        /// 检查哪一种后缀是真实的URL
        /// </summary>
        /// <param name="ImgUrl"></param>
        /// <returns></returns>
        public static String GetImg(String ImgUrl)
        {

            if (WebHelper.GetStatusCode(ImgUrl + ".jpg"))
                return ImgUrl + ".jpg";
            if (WebHelper.GetStatusCode(ImgUrl + ".png"))
                return ImgUrl + ".png";
            return "";
        }

    }
}
